<?php

require_once '../config/Config.php';

class DB extends PDO {

    // single instance of self shared among all instances
    private static $instance = null;
    // db connection vars
    private $dbUser;
    private $dbPass;
    private $dbName;
    private $dbHost;
    public $error_message;

    public static function getInstance() {
        if (!self::$instance instanceof self) {
            self::$instance = new self;
        }
        return self::$instance;
    }

    public function __clone() {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }

//    public function __wakeup() {
//        trigger_error('Deserializing is not allowed.', E_USER_ERROR);
//    }

    function __construct() {

        $config = Config::getConfig("db");

        $this->dbHost = $config['dbhost'];
        $this->dbName = $config['dbname'];
        $this->dbUser = $config['username'];
        $this->dbPass = $config['password'];

        $dsn = "mysql:host={$this->dbHost};dbname={$this->dbName}";
        try {
            parent::__construct($dsn, $this->dbUser, $this->dbPass);
            parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            parent::exec("SET CHARACTER SET utf8");
        } catch (PDOException $e) {
            echo "Database connection error:<br/>";
            echo $e->getMessage();
            die();
        }
    }

    public function verifyUserCredentials($useremail, $password) {
        $useremail = htmlentities($useremail);
        $password = htmlentities($password);

        $query = "SELECT 1 FROM users 
            WHERE email = '" . $useremail . "' AND password = '" . $password . "'";

        $result = $this->query($query);

        return ($result->rowCount() > 0);
    }

    public function get_wisher_id_by_name($name) {

        $name = $this->escape_string($name);

        $query = "SELECT id " .
                "  FROM users " .
                " WHERE email = '" . $name . "'";

        $result = $this->query($query);
        if ($result->num_rows > 0) {
            $row = $result->fetch_row();
            return $row[0];
        } else {
            return null;
        }
    }

    public function get_wishes_by_wisher_id($id) {
        $query = "SELECT id, description, due_date " .
                "   FROM wishes " .
                "  WHERE wisher_id = " . $id;

        $result = $this->query($query);

        return $result;
    }

    public function create_wisher($name, $password) {
        $name = $this->escape_string($name);
        $password = $this->escape_string($password);
        $this->query("INSERT INTO wishers (name, password) VALUES ('" . $name
                . "', '" . $password . "')");
    }

    public function verify_wisher_credentials($name, $password) {
        $name = $this->escape_string($name);
        $password = $this->escape_string($password);

        $result = $this->query("SELECT 1 FROM wishers 
            WHERE name = '" . $name . "' AND password = '" . $password . "'");

        return $result->data_seek(0);
    }

    public function insert_wish($wisherID, $description, $duedate) {
        $description = $this->escape_string($description);

        if ($this->format_date_for_sql($duedate) == null) {
            $this->query("INSERT INTO wishes (wisher_id, description)" .
                    " VALUES (" . $wisherID . ", '" . $description . "')");
        } else {
            $this->query("INSERT INTO wishes (wisher_id, description, due_date)" .
                    " VALUES (" . $wisherID . ", '" . $description . "',"
                    . $this->format_date_for_sql($duedate) . ")");
        }
    }

    function format_date_for_sql($date) {
        if ($date == "")
            return null;
        else {
            $dateParts = date_parse($date);
            return $dateParts["year"] * 10000 + $dateParts["month"] * 100 + $dateParts["day"];
        }
    }

    public function get_wish_by_wish_id($wishID) {
        return $this->query("SELECT id, description, due_date FROM wishes WHERE id= " . $wishID);
    }

    public function update_wish($wishID, $description, $duedate) {
        $description = $this->escape_string($description);
        if ($duedate == '') {
            $this->query("UPDATE wishes SET description = '" . $description . "',
                due_date = NULL where id = " . $wishID);
        } else {
            $this->query("UPDATE wishes SET description = '" . $description .
                    "',due_date = " . $this->format_date_for_sql($duedate)
                    . " where id = " . $wishID);
        }
    }

    public function delete_wish($wishID) {
        $this->query("DELETE FROM wishes WHERE id = " . $wishID);
    }

    public function get_wishes_by_wisher_name($name) {
        $query = "SELECT s.id, s.description, s.due_date " .
                "   FROM wishes s " .
                "   JOIN wishers r ON r.id = s.wisher_id " .
                "  WHERE r.name = '" . $name . "'";

        $result = $this->query($query);

        return $result;
    }

//    public function resetPassword($useremail) {
//        $useremail = htmlentities($useremail);
//
//        // validate email address
//        $return = common::validate_email($useremail);
//
//        if ($return) {
//            $result = $this->query("SELECT 1 FROM users
//                WHERE email = '" . $useremail . "'");
//
//            $return = ($result->rowCount() > 0);
////            $result->close();
//        }
//
//        return $return;
//    }

    public function createUserAccount($useremail, $password) {
        $useremail = $this->escape_string($useremail);
        $password = $this->escape_string($password);


        //createaccount

        return false;
    }

    public function insertRow($table, $values) {
        
    }

}

?>
